package com.ruicar.afs.cloud.afscase.channel.task;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelQuotaInfo;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelQuotaInfoService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author mingzhi.li
 * @Date 2020/6/12
 */

@Slf4j
@Component
@RestController
@AllArgsConstructor
@ApiOperation(value = "临时额度到期逻辑处理")
public class ResidualMarginTask {
    /**
     * 基本信息
     */
    @Autowired
    private ChannelQuotaInfoService channelQuotaInfoService;

    /**
     * 每天上午10点、下午14点、下午16点执行
     */
    @Scheduled(cron = "0 0 10,14,16 * * ?")
    public void start() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        //获取当前日期时间
        Long dayTime = calendar.getTime().getTime();
        //Step1：查询额度信息表数据并更新数据库
        List<ChannelQuotaInfo> list = channelQuotaInfoService.list(Wrappers.<ChannelQuotaInfo>query().lambda());
        List<ChannelQuotaInfo> quotaInfoList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                ChannelQuotaInfo info = list.get(i);
                Long endTime = info.getValidityTermEnd().getTime();
                //判断如果当前日期大于临时额度有效期：表示临时额度已过期，需要将临时额度清零，且剩余额度对应减少
                if (dayTime >= endTime) {
                    //获取剩余额度
                    BigDecimal surplusQuota = info.getSurplusQuota() == null ? BigDecimal.ZERO : info.getSurplusQuota();
                    //获取临时额度
                    BigDecimal tempQuota = info.getTempQuota() == null ? BigDecimal.ZERO : info.getTempQuota();
                    //剩余额度=剩余额度-临时额度
                    info.setSurplusQuota(surplusQuota.subtract(tempQuota));
                    //临时额度清零
                    info.setTempQuota(BigDecimal.ZERO);
                    channelQuotaInfoService.updateById(info);
                    quotaInfoList.add(info);
                }
            }

            //Step2: 调用渠道服务更新渠道子系统额度信息
            channelQuotaInfoService.synchronousLimitToChannel(quotaInfoList);
        }
    }
}
